package com.flute.search.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;

public class XmlObjectUtil {

	public static String toXml(Object obj) {
		if (obj == null)
			throw new NullPointerException();
		XStream xstream = new XStream(new MyXppDriver());
		xstream.processAnnotations(obj.getClass());
		xstream.registerConverter(new DateConverter());
		return xstream.toXML(obj);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T fromXml(Class<T> clazz, String xml) {
		XStream xstream = new XStream(new MyXppDriver());
		xstream.processAnnotations(clazz);
		xstream.registerConverter(new DateConverter());
		return (T) xstream.fromXML(xml);
	}

	public static String readXml(String path) {
		BufferedReader reader = null;
		StringBuilder sb = new StringBuilder("");
		try {
			reader = new BufferedReader(new InputStreamReader(XmlObjectUtil.class
					.getClassLoader().getResourceAsStream(path), Constant.CHARSET));
			String str;
			while ((str = reader.readLine()) != null) {
				sb.append(str).append("\n");
			}

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
			}
		}
		return sb.toString();

	}
}
